/* ===========================================================
 * course.js — 课程详情页脚本（无收藏，含完整字段和注册跳转）
 * =========================================================== */

const DB_NAME    = 'WebDB';
const DB_VERSION = 1;
let   db         = null;
let   currentCourseId = 0;

function openDB() {
  if (db) return Promise.resolve(db);

  return new Promise((resolve, reject) => {
    const req = indexedDB.open(DB_NAME, DB_VERSION);

    req.onupgradeneeded = e => {
      const _db = e.target.result;
      if (!_db.objectStoreNames.contains('courses')) {
        _db.createObjectStore('courses', { keyPath: 'id' });
      }
      if (!_db.objectStoreNames.contains('ref_student_course')) {
        const store = _db.createObjectStore('ref_student_course', { keyPath: ['studentId', 'courseId'] });
        store.createIndex('studentId', 'studentId', { unique: false });
      }
    };

    req.onsuccess = e => {
      db = e.target.result;
      resolve(db);
    };
    req.onerror = e => reject(e.target.error);
  });
}
async function initCoursesData() {
  if (!Array.isArray(window.coursesData) || !window.coursesData.length) {
    console.error('CoursesData is undefined or empty, please confirm that coursesData.exe is loaded correctly');
    return;
  }

  try {
    const d = await openDB();
    const tx = d.transaction('courses', 'readonly');
    const store = tx.objectStore('courses');

    const count = await new Promise(res => {
      const req = store.count();
      req.onsuccess = () => res(req.result);
      req.onerror = () => res(0);
    });
    await tx.done;

    if (count > 0) {
      console.log('[Init] courses already exist, skip initialization');
      return;
    }

    const txW = d.transaction('courses', 'readwrite');
    const storeW = txW.objectStore('courses');

    for (const c of window.coursesData) {
      try {
        storeW.put(c);
      } catch (err) {
        console.error('Writing course data failed:', c, err);
      }
    }
    await txW.done;
    console.log('[Init] courses data write completed');
  } catch (error) {
    console.error('Failed to initialize courses data:', error);
  }
}


async function dbGet(storeName, key) {
  const d = await openDB();
  return new Promise((resolve, reject) => {
    const tx = d.transaction(storeName, 'readonly');
    const req = tx.objectStore(storeName).get(key);
    req.onsuccess = e => resolve(e.target.result);
    req.onerror = e => reject(e.target.error);
  });
}

async function dbPut(storeName, value) {
  const d = await openDB();
  return new Promise((resolve, reject) => {
    const tx = d.transaction(storeName, 'readwrite');
    const req = tx.objectStore(storeName).put(value);
    req.onsuccess = () => resolve(true);
    req.onerror = e => reject(e.target.error);
  });
}

function getUserId() {
  const token = localStorage.getItem('token');
  return token && token.trim() ? token.trim() : null;
}

function showTip(text, duration = 2000) {
  const tip = document.createElement('div');
  tip.textContent = text;
  tip.style.cssText = `
    position: fixed;
    left: 50%;
    top: 25%;
    transform: translate(-50%, -50%);
    background: rgba(0, 0, 0, 0.75);
    color: white;
    padding: 8px 16px;
    border-radius: 4px;
    font-size: 14px;
    z-index: 9999;
    pointer-events: none;
    transition: opacity 0.3s;
  `;
  document.body.appendChild(tip);
  setTimeout(() => {
    tip.style.opacity = '0';
    setTimeout(() => tip.remove(), 300);
  }, duration);
}

function populateCourseDetails(c) {
  if (!c) return;
  const get = id => document.getElementById(id);

  get('courseCover')?.setAttribute('src', c.cover_image || 'default-cover.jpg');
  get('courseCover')?.setAttribute('alt', `${c.title || 'course'} 封面`);
  get('courseTitle').textContent       = c.title || 'untitled';
  get('courseCategory').textContent    = c.category || 'Unclassified';
  get('courseTeacher').textContent     = c.teacher || 'Unknown teacher';
  get('courseCreatedAt').textContent   = c.created_at ? new Date(c.created_at).toLocaleDateString() : 'Unknown time';
  get('courseUpdatedAt').textContent   = c.updated_at ? new Date(c.updated_at).toLocaleDateString() : 'not updated';
  get('courseIntro').textContent       = c.courseIntro || 'No introduction available at the moment';
  get('courseDescription').textContent = c.description || 'No detailed description available at the moment';
  get('registerCount').textContent     = c.registerCount || 0;
  get('likesCount').textContent        = c.likes || 0;
  get('enableComments').textContent    = c.enableComments ? 'open' : 'close';

  ['intro', 'plan', 'catalog', 'assessment'].forEach(tab => {
    const div = get(`tab-${tab}`);
    if (!div) return;
    switch (tab) {
      case 'intro': div.textContent = c.courseIntro || 'None'; break;
      case 'plan': div.textContent = c.teachingPlan || 'None'; break;
      case 'catalog': div.textContent = c.catalog || 'None'; break;
      case 'assessment': div.textContent = c.assessmentStandard || 'None'; break;
    }
  });

  const emailEl = get('teacherEmail');
  if (emailEl) {
    emailEl.textContent = c.teacherEmail || 'Email not provided';
    emailEl.href = c.teacherEmail ? `mailto:${c.teacherEmail}` : '#';
  }
  const teacherNameEl = get('teacherName');
  if (teacherNameEl) teacherNameEl.textContent = c.teacher || 'Anonymous lecturer';
}

async function hasRegistered(courseId) {
  const user = getUserId();
  if (!user) return false;

  const d = await openDB();
  const tx = d.transaction('ref_student_course', 'readonly');
  const store = tx.objectStore('ref_student_course');
  const req = store.get([user, courseId]);

  return new Promise(resolve => {
    req.onsuccess = e => resolve(!!e.target.result);
    req.onerror = () => resolve(false);
  });
}

async function registerCourse(courseId) {
    console.log('RegistCourse is called, courseId=', courseId);
  const btn = document.getElementById('registerCourseBtn');
  const user = getUserId();

  if (!btn) return;
  if (!user) {
    showTip('please log in first');
    return;
  }

  if (btn.textContent.trim() === 'Start learning') {
     console.log('Jump to video.exe page');
    location.href = `video.html?courseId=${courseId}`;
    return;
  }

  const db = await openDB();
  const tx = db.transaction(['ref_student_course', 'courses'], 'readwrite');
  const refStore = tx.objectStore('ref_student_course');
  const courseStore = tx.objectStore('courses');

  // 检查是否已注册
  const existing = await new Promise(res => {
    const r = refStore.get([user, courseId]);
    r.onsuccess = e => res(e.target.result);
    r.onerror = () => res(null);
  });

  if (existing) {
    showTip('This course has already been registered');
    btn.textContent = 'Start learning';
    btn.classList.add('registered');
    return;
  }

  // 写入注册记录
  await new Promise((resolve, reject) => {
    const r = refStore.add({ studentId: user, courseId });
    r.onsuccess = () => resolve();
    r.onerror = e => reject(e.target.error);
  });

  // 更新课程注册人数
  const course = await new Promise(res => {
    const r = courseStore.get(courseId);
    r.onsuccess = e => res(e.target.result);
    r.onerror = () => res(null);
  });

  if (course) {
    course.registerCount = (course.registerCount || 0) + 1;
    await new Promise((resolve, reject) => {
      const r = courseStore.put(course);
      r.onsuccess = () => resolve();
      r.onerror = e => reject(e.target.error);
    });
  }

  if (tx.commit) tx.commit();

  showTip('registered successfully');
  btn.textContent = 'Start learning';
  btn.classList.add('registered');
  

}



/*收藏* */
const favKey = (u, cid)       => `fav_${u}_${cid}`;
const isFav  = (u, cid)       => localStorage.getItem(favKey(u, cid)) === 'true';
const setFav = (u, cid, val)  => localStorage.setItem(favKey(u, cid), val ? 'true' : 'false');

async function likeCourse(courseId) {
  const starEl = document.querySelector('.star-icon');
  const user   = getUserId();
  if (!user) return showTip('please log in first');

  const course = await dbGet('courses', courseId);
  if (!course) { showTip('Course does not exist'); return; }

  if (isFav(user, courseId)) {
    course.likes = Math.max((course.likes || 1) - 1, 0);
    setFav(user, courseId, false);
    starEl && (starEl.style.fill = 'none');
    showTip('Unsubscribed');
  } else {
    course.likes = (course.likes || 0) + 1;
    setFav(user, courseId, true);
    starEl && (starEl.style.fill = 'gold');
    showTip('This course has been bookmarked');
  }

  await dbPut('courses', course);
  const cnt = document.getElementById('likesCount');
  if (cnt) cnt.textContent = course.likes;
}
function onStarClick() { likeCourse(currentCourseId); }









document.addEventListener('DOMContentLoaded', async () => {
  await initCoursesData();

  currentCourseId = Number(new URLSearchParams(location.search).get('courseId'));
  if (!currentCourseId) return;

  const btn = document.getElementById('registerCourseBtn');
  const container = document.querySelector('.register-btn-container');
  const star = document.querySelector('.star-icon');

  if (!btn || !container) return;

  // 给按钮绑定点击事件
  btn.onclick = () => registerCourse(currentCourseId);

  // 给父容器绑定点击事件，转发给按钮点击处理
  container.onclick = (e) => {
    // 如果点击的是父容器本身或者非按钮子元素，则触发按钮点击
    if (e.target === container || !btn.contains(e.target)) {
      btn.click();
    }
  };

  
  if (star) {
    star.onclick = onStarClick;

    // 根据用户是否收藏当前课程设置星星颜色
    const user = getUserId();
    if (user) {
      const fav = await isFav(user, currentCourseId);
      star.style.fill = fav ? 'gold' : 'none';
    } else {
      star.style.fill = 'none';
    }
  }


  const course = await dbGet('courses', currentCourseId);
  if (course) populateCourseDetails(course);
  else console.warn(`Course ID=${CurrentCourseId} not found`);

  const user = getUserId();
  if (user) {
    const registered = await hasRegistered(currentCourseId);
    if (registered) {
      btn.textContent = 'Start learning';
      btn.classList.add('registered');
    } else {
      btn.textContent = 'Registered Course';
      btn.classList.remove('registered');
    }
  } else {
    btn.textContent = 'Registered Course';
    btn.classList.remove('registered');
  }
});

